<template>
  <view class="conversation-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-content">
        <view class="back-section" @click="goBack">
          <text class="back-icon">←</text>
          <text class="header-title">{{ conversationTitle }}</text>
        </view>
        <view class="header-actions">
          <button class="share-btn" @click="shareConversation">
            <text class="share-icon">📤</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 消息列表 -->
    <scroll-view
      class="messages-list"
      scroll-y="true"
      :scroll-top="scrollTop"
      scroll-with-animation="true"
      @scrolltolower="loadMoreMessages"
    >
      <view v-if="messages.length === 0 && !loading" class="empty-state">
        <text class="empty-icon">💬</text>
        <text class="empty-title">开始对话</text>
        <text class="empty-desc">发送您的第一个问题吧</text>
      </view>

      <view v-else class="messages-container">
        <view
          v-for="message in messages"
          :key="message.id"
          class="message-item"
          :class="message.role === 'user' ? 'message-user' : 'message-ai'"
        >
          <view class="message-avatar">
            <text v-if="message.role === 'user'" class="avatar-user">👤</text>
            <text v-else class="avatar-ai">🤖</text>
          </view>
          <view class="message-content">
            <view class="message-text">{{ message.content }}</view>
            <view class="message-time">{{
              formatTime(message.createdAt)
            }}</view>

            <!-- AI消息的引用来源 -->
            <view
              v-if="
                message.role === 'assistant' &&
                message.sources &&
                message.sources.length > 0
              "
              class="message-sources"
            >
              <text class="sources-title">📚 参考来源：</text>
              <view
                v-for="(source, index) in message.sources"
                :key="index"
                class="source-item"
              >
                <text class="source-content">{{ source.content }}</text>
                <text class="source-info"
                  >{{ source.source }} (相似度:
                  {{ (source.similarity * 100).toFixed(1) }}%)</text
                >
              </view>
            </view>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="loadingMore" class="loading-more">
          <text>加载中...</text>
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-section">
      <view class="input-container">
        <textarea
          v-model="inputMessage"
          class="message-input"
          placeholder="输入您的问题..."
          :disabled="sending"
          :maxlength="1000"
          auto-height="true"
          @confirm="sendMessage"
        />
        <button
          class="send-btn"
          :class="{ 'send-btn-disabled': !inputMessage.trim() || sending }"
          @click="sendMessage"
          :disabled="!inputMessage.trim() || sending"
        >
          <text v-if="!sending" class="send-icon">📤</text>
          <text v-else class="sending-icon">⏳</text>
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from "vue";
import { chatAPI } from "@/api/index";

// 页面参数
const conversationId = ref("");
const conversationTitle = ref("");

// 响应式数据
const messages = ref([]);
const inputMessage = ref("");
const sending = ref(false);
const loading = ref(false);
const loadingMore = ref(false);
const scrollTop = ref(0);

// 计算属性
const hasMessages = computed(() => messages.value.length > 0);

// 生命周期
onMounted(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;

  conversationId.value = options.id;
  conversationTitle.value = decodeURIComponent(options.title || "新对话");

  loadMessages();
});

// 加载消息历史
const loadMessages = async () => {
  if (!conversationId.value) return;

  try {
    loading.value = true;
    const response = await chatAPI.getHistory(conversationId.value);

    if (response && Array.isArray(response)) {
      messages.value = response;
      // 滚动到底部
      await nextTick();
      scrollToBottom();
    }
  } catch (error) {
    console.error("加载消息失败:", error);
    uni.showToast({
      title: "加载失败，请重试",
      icon: "none",
    });
  } finally {
    loading.value = false;
  }
};

// 发送消息
const sendMessage = async () => {
  const message = inputMessage.value.trim();
  if (!message || sending.value) return;

  // 添加用户消息到列表
  const userMessage = {
    id: `user_${Date.now()}`,
    role: "user",
    content: message,
    createdAt: new Date().toISOString(),
  };
  messages.value.push(userMessage);

  // 清空输入框
  inputMessage.value = "";

  // 滚动到底部
  await nextTick();
  scrollToBottom();

  try {
    sending.value = true;

    // 发送到后端
    const response = await chatAPI.askQuestion(message, conversationId.value);

    if (response && response.answer) {
      // 添加AI回复
      const aiMessage = {
        id: `ai_${Date.now()}`,
        role: "assistant",
        content: response.answer,
        createdAt: new Date().toISOString(),
        sources: response.sources || [],
      };
      messages.value.push(aiMessage);

      // 更新对话ID（如果后端返回新的）
      if (
        response.conversationId &&
        response.conversationId !== conversationId.value
      ) {
        conversationId.value = response.conversationId;
      }

      // 滚动到底部
      await nextTick();
      scrollToBottom();
    } else {
      throw new Error("返回的回答格式不正确");
    }
  } catch (error) {
    console.error("发送消息失败:", error);

    // 移除用户消息（发送失败）
    messages.value.pop();

    uni.showToast({
      title: "发送失败，请重试",
      icon: "none",
    });
  } finally {
    sending.value = false;
  }
};

// 加载更多消息（分页加载）
const loadMoreMessages = async () => {
  if (loadingMore.value) return;

  try {
    loadingMore.value = true;
    // 这里可以实现分页加载历史消息的逻辑
    // 暂时不实现，因为后端API没有分页参数
  } catch (error) {
    console.error("加载更多消息失败:", error);
  } finally {
    loadingMore.value = false;
  }
};

// 滚动到底部
const scrollToBottom = () => {
  scrollTop.value = 999999;
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 分享对话
const shareConversation = () => {
  // 实现分享功能
  uni.showToast({
    title: "分享功能开发中",
    icon: "none",
  });
};

// 格式化时间
const formatTime = (dateString) => {
  const date = new Date(dateString);
  const now = new Date();
  const diff = now - date;

  const minutes = Math.floor(diff / (1000 * 60));
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));

  if (minutes < 1) return "刚刚";
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  if (days < 7) return `${days}天前`;

  return date.toLocaleDateString();
};
</script>

<style scoped>
.conversation-container {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.header {
  background-color: #fff;
  border-bottom: 1px solid #e0e0e0;
  padding: 10px 0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.back-section {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.back-icon {
  font-size: 20px;
  color: #333;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.share-btn {
  background: none;
  border: none;
  padding: 8px;
}

.share-icon {
  font-size: 18px;
  color: #666;
}

.messages-list {
  flex: 1;
  padding: 20px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 20px;
}

.empty-title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.empty-desc {
  font-size: 14px;
  color: #666;
}

.messages-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message-item {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.message-user {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  background-color: #f0f0f0;
  margin: 0 8px;
}

.avatar-user {
  font-size: 22px;
  line-height: 1;
}

.avatar-ai {
  font-size: 22px;
  line-height: 1;
}

.message-content {
  flex: 1;
  max-width: 70%;
}

.message-user .message-content {
  align-items: flex-end;
}

.message-text {
  background-color: #007aff;
  color: white;
  padding: 12px 16px;
  border-radius: 18px;
  font-size: 16px;
  line-height: 1.4;
  word-wrap: break-word;
}

.message-ai .message-text {
  background-color: white;
  color: #333;
  border: 1px solid #e0e0e0;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  text-align: right;
}

.message-ai .message-time {
  text-align: left;
}

.message-sources {
  margin-top: 10px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border-left: 3px solid #007aff;
}

.sources-title {
  font-size: 12px;
  color: #666;
  font-weight: 600;
  margin-bottom: 8px;
  display: block;
}

.source-item {
  margin-bottom: 8px;
  padding: 8px;
  background-color: white;
  border-radius: 6px;
}

.source-content {
  font-size: 13px;
  color: #333;
  line-height: 1.4;
  display: block;
  margin-bottom: 4px;
}

.source-info {
  font-size: 11px;
  color: #999;
  display: block;
}

.loading-more {
  text-align: center;
  padding: 20px;
  color: #999;
  font-size: 14px;
}

.input-section {
  background-color: #fff;
  border-top: 1px solid #e0e0e0;
  padding: 15px 20px;
  padding-bottom: calc(15px + env(safe-area-inset-bottom));
}

.input-container {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.message-input {
  flex: 1;
  border: 1px solid #e0e0e0;
  border-radius: 20px;
  padding: 12px 16px;
  font-size: 16px;
  max-height: 120px;
  min-height: 44px;
  resize: none;
}

.send-btn {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  background-color: #007aff;
  color: white;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.send-btn-disabled {
  background-color: #ccc;
}

.send-icon,
.sending-icon {
  font-size: 18px;
}

.sending-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
